﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;

using Framework;
using SchemaMonitor;
using SchemaMonitor.json;

public partial class usercontrols_UCData : CUsercontrolWithTable
{
	public int TypeId			{ get { return CWeb.RequestInt("typeId", CSession.TypeId); } }
	public string SearchData	{ get { return CWeb.RequestStr("search", CSession.SearchData); } }
	public bool IsEdit			{ get { return CWeb.RequestStr("edit").Length > 0 || CWeb.RequestStr("btnSaveData").Length > 0; } }


	private CUser _user;

	public void PageInit(CUser user)
	{
		_user = user;

		//Form State
		txtSearch.Text = this.SearchData;
		chkArchived.Checked = CSession.SearchArchived;

		ctrlPagingNodes.FriendlyUrl = "~/default.aspx" + this.Page.Form.Action;


		//types
		foreach (KeyValuePair<int, CNodeList> i in _user.All.IndexByTypeId)//.CountByTypes())
		{
			var t = CType.Cache.GetById(i.Key);
			if (null == t)
				continue;	//MISSING TYPE!!!

			var n = t.TypeName;
			if (n.Length == 0)
				n = t.Signatures.Shortest;
			n = CUtilities.NameAndCount(n, i.Value);
			CDropdown.Add(ddTypes, n, i.Key);
		}
		CDropdown.SetValue(ddTypes, this.TypeId.ToString());

	}
	private void Page_PreRender(object sender, EventArgs e)
	{
		if (Page.IsPostBack)
			if (CWeb.RequestStr("__EVENTTARGET") == "dd")
			{
				var id = CWeb.RequestStr("dd");
				CDropdown.SetValue(dd, id);
				txtSearch.Text = id;
				btnSearch_Click(null, null);
			}
	}

	public void ShowData()
	{
		CSession.TypeId = CDropdown.GetInt(ddTypes);

		//Archived
		var a = _user.All;
		if (CSession.SearchArchived)
			a = _user.Archived;

		//By type
		var forType = a.GetByTypeId(CSession.TypeId);
		var temp = forType;

		//Apply search
		var search = txtSearch.Text;
		if (!string.IsNullOrEmpty(search))
			forType = forType.Search(search);

		//apply paging
		var page = new CNodeList(ctrlPagingNodes.Display(forType));
		ctrlPaging2.Info = ctrlPagingNodes.Info;
		var pi = ctrlPaging2.Info;



		//Custom Display
		CType t = CType.Cache.GetById(CSession.TypeId);
		switch (t.TypeName)
		{
			case "user":
				ShowPage_User(page);
				return;

			case "comment":
				ShowPage_Comment(page);
				return;

			case "photo":
				ShowPage_Photo(page);
				return;

			case "post":
				ShowPage_Post(page);
				return;

			case "album":
				ShowPage_Album(page);
				return;
		}


		//Default
		var tags = ShowPage_GetTags(page);

		if (tags.Count < 100)
			ShowPage_Custom(page, tags);
		else
			ShowPage_Raw(page, ctrlPagingNodes.Info);

	}




	#region Fully Custom

	private void ShowPage_User(CNodeList page)
	{
		tbl.Visible = true;

		var th = new TableHeaderRow();
		tbl.Rows.Add(th);
		Th(th, "id");
		Th(th, "name");
		Th(th, "fields");

		foreach (var i in page)
		{
			var user = new CSoftUser(i.Root, _user);

			var tr = new TableRow();
			tbl.Rows.Add(tr);
			if (tbl.Rows.Count % 2 == 0)
				tr.CssClass = "alt_row";

			var r = i.Root;
			IdCell(tr, r);
			Td(tr, user.Name);
			Td(tr, CUtilities.CountSummary(r.Fields.Count, "field", "none")).ToolTip = CUtilities.ListToString(r.Fields.Tags, "\r\n");
		}
	}
	private void ShowPage_Photo(CNodeList page)
	{
		tbl.Visible = true;


		var tr = new TableRow();
		tbl.Rows.Add(tr);

		var cols = 5;
		var index = 0;
		foreach (var i in page)
		{
			if (index++ % cols == 0)
			{
				tr = new TableRow();
				tbl.Rows.Add(tr);
			}

			var photo = new CSoftPhoto(i.Root, _user);

			if (tbl.Rows.Count % 2 == 0)
				tr.CssClass = "alt_row";

			var td = IdCell2(tr, i);
			ImgWithLink(td, i.Root.Id);
		}
		while (tr.Controls.Count < cols)
			tr.Cells.Add(new TableCell());
	}
	private void ShowPage_Comment(CNodeList page)
	{
		tbl.Visible = true;

		var th = new TableHeaderRow();
		tbl.Rows.Add(th);
		Th(th, "id");
		Th(th, "from");
		Th(th, "message");
		Th(th, "likes");
		Th(th, "tags");
		Th(th, "fields");


		foreach (var i in page)
		{
			var comment = new CSoftComment(i.Root, _user);

			var tr = new TableRow();
			tbl.Rows.Add(tr);
			if (tbl.Rows.Count % 2 == 0)
				tr.CssClass = "alt_row";

			var r = i.Root;
			IdCell2(tr, i);

			var tdc = Td(tr, comment.Name);
			if (comment.HasFrom)
			{
				var from = comment.From;
				string url = CSitemap.DataView(from.Id, CSoftUser.Type.TypeId);
				Link(tdc, url);
			}

			Td(tr, comment.Message);
			Td(tr, !comment.HasLikes ? string.Empty : CUtilities.CountSummary(comment.LikeCount, "like", string.Empty));
			Td(tr, !comment.HasTags ? string.Empty : CUtilities.CountSummary(comment.Tags, "tag", string.Empty));
			Td(tr, CUtilities.CountSummary(r.Fields.Count, "field", "none")).ToolTip = CUtilities.ListToString(r.Fields.Tags, "\r\n");

			/*
			var id1 = i.Root.Id1;
			var id2 = i.Root.Id2;
			var guid1 = CNodeRoot.Str2Guid(id1.ToString());
			var guid2 = CNodeRoot.Str2Guid(id2.ToString());
			var node1 = _user.All.GetById(guid1);
			var node2 = _user.All.GetById(guid2);
			var s1 = null == node1 ? "?" : node1.Type.TypeName + ": " + CUtilities.Truncate(node1.Root.Name);
			var s2 = null == node2 ? "?" : node2.Type.TypeName + ": " + CUtilities.Truncate(node2.Root.Name);
			Td(tr, string.Concat(s1, "<br/>", s1));
			*/
		}
	}
	private void ShowPage_Album(CNodeList page)
	{
		tbl.Visible = true;	

		var th = new TableHeaderRow();
		tbl.Rows.Add(th);
		Th(th, "id");
		Th(th, "name");
		Th(th, "size");
		Th(th, "cover");
		Th(th, "privacy");
		Th(th, "type");
		Th(th, "description");


		foreach (var i in page)
		{

			var tr = new TableRow();
			tbl.Rows.Add(tr);
			if (tbl.Rows.Count % 2 == 0)
				tr.CssClass = "alt_row";

			var r = i.Root;
			var album = new CSoftAlbum(i.Root, _user);

			IdCell(tr, r);

			var tdc = Td(tr, album.Name);
			Td(tr, album.Size);

			if (album.CoverPhotoId.HasValue)
				ImgWithLink(tr, album.CoverPhotoId.Value);
			else
				Td(tr, string.Empty);

			Td(tr, album.Privacy);
			Td(tr, album.Type);
			Td(tr, album.Description);
		}
	}
	private void ShowPage_Post(CNodeList page)
	{
		tbl.Visible = true;

		var th = new TableHeaderRow();
		tbl.Rows.Add(th);
		Th(th, "id");
		Th(th, "picture");
		Th(th, "message");
		Th(th, "attach.");
		Th(th, "stored");
		Th(th, "comm");
		Th(th, "tags");
		Th(th, "type");
		Th(th, "from");
		Th(th, "privacy");
		Th(th, "fields");


		foreach (var i in page)
		{
			var tr = new TableRow();
			tbl.Rows.Add(tr);
			if (tbl.Rows.Count % 2 == 0)
				tr.CssClass = "alt_row";

			var post = new CSoftPost(i.Root, _user);

			var r = i.Root;

			var id = IdCell2(tr, i);
			if (post.ObjectId.Length > 0)
			{
				var div = new Panel();
				id.Controls.AddAt(2,div);
				var lbl = new Label();
				div.Controls.Add(lbl);
				lbl.Text = post.ObjectId;
			}

			
			RawImg(tr, post.Picture);

			var m = Td(tr, string.IsNullOrEmpty(post.Message) ? post.Name : post.Message);
			if (post.Description.Length > 0)
			{
				var divDesc = new Panel();
				m.Controls.Add(divDesc);

				var lblDesc = new Label();
				lblDesc.Text = post.Description;
				divDesc.Controls.Add(lblDesc);
			}

			Td(tr, post.CountAttachments);
			Td(tr, post.PhotoIds.Count);
			Td(tr, post.Comments.Count);
			var s = CUtilities.ListToHtml(post.Labels_O2O.Metatags.Names);
			if (s.Length > 0)
				s = string.Concat("<b>", CUtilities.ListToHtml(post.Labels_O2O.Metatags.Names), "</b>");
			if (post.Labels.Count > 0)
				s = string.Concat(s, "<br/>", CUtilities.ListToHtml(post.Labels.Metatags.Names));
			Td(tr, s);//  post.Labels.Count + post.Labels_O2O.Count).ToolTip = CUtilities.ListToString(post.Metatags.Names);
			Td(tr, post.Caption + " " + post.Type);

			var from = post.From;
			if (null != from)
			{
				string url = CSitemap.DataView(from.Id, CSoftUser.Type.TypeId);
				Link(Td(tr, post.From.Name), url);
			}
			else
				Td(tr, "");


			
			Td(tr, post.Privacy);
			Td(tr, post.Fields.Count);
		}
	}
	#endregion



	#region ShowData Helpers
	private List<string> ShowPage_GetTags(CNodeList page)
	{
		var tags = new List<string>() { "id" };
		foreach (var i in page)
			foreach (var j in i.Root.Tags)
				if (!tags.Contains(j))
					tags.Add(j);
		return tags;
	}

	private void ShowPage_Custom(CNodeList page, List<string> tags)
	{
		tbl.Visible = true;
		var th = new TableHeaderRow();
		tbl.Rows.Add(th);
		foreach (var i in tags)
			if (i != CNodeRoot.CT && i != "story")
				Th(th, i);


		foreach (var i in page)
		{
			var tr = new TableRow();
			tbl.Rows.Add(tr);
			if (tbl.Rows.Count % 2 == 0)
				tr.CssClass = "alt_row";


			var ff = i.Root.Fields;
			foreach (var j in tags)
			{
				string s = string.Empty;
				if (ff.Has(j))
					s = i.Root.GetString(j);

				if (j == CNodeRoot.CT)
					continue;
				if (j == "story")
					continue;

				if (j.EndsWith("_time"))
				{
					var d = SchemaMonitor.html.CHtml.ToDate(s);
					Td(tr, CUtilities.Timespan(d)).ToolTip = CUtilities.LongDateTime(d);
				}
				else if (j == "id")
				{
					IdCell(tr, i, tags);
				}
				else
				{
					if (j == "comments" && ff.Has(j))
						s = Comments(ff[j]);
					var td = Td(tr, s);

					if (j == CNodeRoot.PHOTO_IDS && ff.Has(j))
						td.Text = CUtilities.CountSummary(ff[j].List.Count, "photo");


					if ((j == "picture" || j == "icon") && ff.Has(j))
					{
						long id = 0;
						var sid = td.Text;
						try
						{
							sid = System.IO.Path.GetFileNameWithoutExtension(td.Text);
						}
						catch { }

						if (long.TryParse(sid, out id))
						{
							var div = new Panel();
							div.Style.Add("margin-top", "10px");
							var lit = new HyperLink();
							div.Controls.Add(lit);
							lit.Text = td.Text;
							tr.Cells[0].Controls.Add(div);

							//td.Controls.Add(lit);
							div = new Panel();
							td.Controls.Add(div);
							var img = new Image();
							img.ImageUrl = CSitemap.Photo(id);
							div.Controls.Add(img);
							img.Width = new Unit(50);
						}
						else
						{
							var img = new Image();
							img.ImageUrl = ff[j].AsString;
							//img.Width = new Unit(50);
							//img.ToolTip = td.Text;
							td.Text = string.Empty;
							td.Controls.Add(img);
						}
					}
				}
			}
		}

	}
	private TableCell IdCell(TableRow tr, SchemaMonitor.CNode i, List<string> tags)
	{
		return IdCell2(tr, i);
	}

	private string Comments(CField f)
	{
		var sb = new StringBuilder();
		var nodes = f.AsPointerList(_user.All);
		foreach (var k in nodes)
		{
			var user = k.Root.GetString("name");
			var time = k.Root.GetString("created_time");
			var message = k.Root.GetString("message");
			sb.Append("<b>").Append(user).Append("</b> ");
			sb.Append(HttpUtility.HtmlEncode(message));
			sb.Append("<br><i><sub>").Append(time).Append("</sub></i>");
			sb.AppendLine("<hr>");
		}
		return sb.ToString();
	}
	private void ShowPage_Raw(CNodeList page, CPagingInfo pi)
	{
		foreach (var i in page)
			UCNode(plhNodes).DisplayAll(i, 1 + page.IndexOf(i) + pi.Offset, _user);
	}
	#endregion


	#region Private - Usercontrols
	private static usercontrols_UCNode UCNode(Control target)
	{
		Control ctrl = target.Page.LoadControl("~/usercontrols/UCNode.ascx");
		target.Controls.Add(ctrl);
		return (usercontrols_UCNode)ctrl;
	}
	#endregion






	protected void dd_SelectedIndexChanged(object sender, EventArgs e)
	{
		var dd = (DropDownList)sender;
		txtSearch.Text = dd.SelectedValue;
		btnSearch_Click(sender, e);
	}

	protected void btnSearch_Click(object sender, EventArgs e)
	{
		CSession.SearchData = txtSearch.Text;
		CSession.SearchArchived = chkArchived.Checked;
	}

	protected void ddTypes_SelectedIndexChanged(object sender, EventArgs e)
	{
		var dd = (DropDownList)sender;
		CSession.TypeId = CDropdown.GetInt(dd);
		CSession.SearchData = string.Empty;
		CSession.SearchArchived = false;
		Response.Redirect("~/");
	}
	///Obsolete
}